import { createStore } from 'vuex';
import { THEMES } from '@/utils/constants';
import { cookieTool, base64, localCache } from '@/utils/common';
import config from '@/config/config';

export default createStore({
  state: {
    config: config.app,
    currentTheme: localCache.get('theme') || THEMES.DARK,
    userInfo: null,
  },
  mutations: {
    setCurrentTheme(state, theme) {
      localCache.set('theme', theme);
      state.currentTheme = theme;
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
  },
  getters: {
    isLogined(state) {
      if (state.userInfo === null) return false;
      return true;
    },
    userInfo(state) {
      return state.userInfo;
    },
    getEditorTheme(state) {
      return state.currentTheme === THEMES.DARK ? THEMES.editor.DARK : THEMES.editor.LIGHT;
    },
    getMenuTheme(state) {
      console.log('menu theme');
      return state.currentTheme === THEMES.DARK ? THEMES.menu.DARK : THEMES.menu.LIGHT;
    },
  },
  actions: {
    login(context, userInfo) {
      cookieTool.setCookie('userInfo', base64.encode(JSON.stringify(userInfo)));
      context.commit('setUserInfo', userInfo);
    },
    logout(context) {
      cookieTool.setCookie('userInfo', '', { exMinute: 0 });
      context.commit('setUserInfo', null);
    },
    themeChanged(context, theme) {
      context.commit('setCurrentTheme', theme);
    },
  },
  modules: {},
});
